package com.example.lxx.stickyexpandview.view;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.example.lxx.stickyexpandview.CustomersAdapter;
import com.example.lxx.stickyexpandview.R;
import com.example.lxx.stickyexpandview.model.EsalerAllCustomerModel;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lxx on 2017/11/9 0009.
 */

public class FloatExpandView extends RelativeLayout{

    /**
     * 下拉头的View
     */
    private View header;
    /**
     * 头的布局参数
     */
    private ViewGroup.MarginLayoutParams headerLayoutParams;
    /**
     * 头的高度
     */
    private RecyclerView recyclerview;
    private RelativeLayout rlHeadView;

    private int hideHeaderHeight;
    private Context mContext;

    private boolean ableToPull;
    private float yDown;
    private List mList;
    private int mFirstVisiblePos;
    private RecyclerView mRecyclerView;
    private CustomersAdapter mAdapter;


    public FloatExpandView(Context context) {
        this(context, null, 0);
    }

    public FloatExpandView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FloatExpandView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        mList = new ArrayList();
        header = LayoutInflater.from(context).inflate(R.layout.view_float_expand, null,false);
        mRecyclerView = header.findViewById(R.id.recycler_view_ll);
        rlHeadView  =header.findViewById(R.id.rl_head_view);

    }

    private void initRecycler() {

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("gggg", "onScrolled: 列表滑动2");

                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                //判断是当前layoutManager是否为LinearLayoutManager,只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                    //获取最后一个可见view的位置
                    int lastItemPosition = linearManager.findLastVisibleItemPosition();
                    //获取第一个可见view的位置

                    mFirstVisiblePos = linearManager.findFirstVisibleItemPosition();
                    Log.d("gggg", "第一个可见view的位置: " + mFirstVisiblePos);

                    if (mList.get(mFirstVisiblePos) instanceof EsalerAllCustomerModel) {
                        EsalerAllCustomerModel model = (EsalerAllCustomerModel) mList.get(mFirstVisiblePos);
                        Log.d("gggg", "第一个可见view: " + model.getName());
                    }

                }
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        recyclerview = (RecyclerView) getChildAt(1);

    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);

       /* hideHeaderHeight = -header.getHeight();
        headerLayoutParams = (MarginLayoutParams) header.getLayoutParams();
        headerLayoutParams.topMargin = hideHeaderHeight;*/

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float yMove = 0;
        int distance = 0;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                yDown = event.getRawY();
                Log.d("gggg", "手指按下onTouch: " );
                return true;
            case MotionEvent.ACTION_MOVE:
                yMove = event.getRawY();
                distance = (int) (yMove - yDown);

                Log.d("gggg", "滑动距离onTouch: " + distance);

                // 如果手指是下滑状态，并且下拉头是完全隐藏的，就屏蔽下拉事件
                if (distance <= 0 && headerLayoutParams.topMargin <= hideHeaderHeight) {
                    return false;
                }


                // 通过偏移下拉头的topMargin值，来实现下拉效果
                headerLayoutParams.topMargin = (distance / 2) + hideHeaderHeight;
                header.setLayoutParams(headerLayoutParams);
                break;
            case MotionEvent.ACTION_UP:
                Log.d("gggg", "手指抬起onTouch: " );
                break;
            default:
                break;
        }
        return super.onTouchEvent(event);
    }

   /* @Override
    public boolean onTouch(View v, MotionEvent event) {
        float yMove = 0;
        int distance = 0;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                yDown = event.getRawY();
                Log.d("gggg", "手指按下onTouch: " );
                return true;
            case MotionEvent.ACTION_MOVE:
                yMove = event.getRawY();
                distance = (int) (yMove - yDown);

                Log.d("gggg", "滑动距离onTouch: " + distance);

                // 如果手指是下滑状态，并且下拉头是完全隐藏的，就屏蔽下拉事件
                if (distance <= 0 && headerLayoutParams.topMargin <= hideHeaderHeight) {
                    return false;
                }


                // 通过偏移下拉头的topMargin值，来实现下拉效果
                headerLayoutParams.topMargin = (distance / 2) + hideHeaderHeight;
                header.setLayoutParams(headerLayoutParams);
                break;
            case MotionEvent.ACTION_UP:
                Log.d("gggg", "手指抬起onTouch: " );
                break;
            default:
                break;
        }
        return false;
    }*/

    /**
     * 根据当前ListView的滚动状态来设定 {@link #ableToPull}
     * 的值，每次都需要在onTouch中第一个执行，这样可以判断出当前应该是滚动ListView，还是应该进行下拉。
     * @param event
     */
    private void setIsAbleToPull(MotionEvent event) {
        View firstChild = recyclerview.getChildAt(0);
        if (firstChild != null) {
            if (mFirstVisiblePos == 0 && firstChild.getTop() == 0) {
                if (!ableToPull) {
                    yDown = event.getRawY();
                }
                // 如果首个元素的上边缘，距离父布局值为0，就说明ListView滚动到了最顶部，此时应该允许下拉刷新
                ableToPull = true;
            } else {
                if (headerLayoutParams.topMargin != hideHeaderHeight) {
                    headerLayoutParams.topMargin = hideHeaderHeight;
                    header.setLayoutParams(headerLayoutParams);
                }
                ableToPull = false;
            }
        } else {
            // 如果ListView中没有元素，也应该允许下拉刷新
            ableToPull = true;
        }
    }

    public void setDataList(List list,BaseMultiItemQuickAdapter adapter){
        mList = list;
        mAdapter = new CustomersAdapter(mList);
        mAdapter = (CustomersAdapter) adapter;

        initRecycler();
        mAdapter.notifyDataSetChanged();
    }


}
